from odoo import fields, models
from odoo.exceptions import UserError

PRODUCT_CATEGORY = [('finished', '成品'), ('semi_finished', '半成品'), ('materials', '原料')]


class InheritProduct(models.Model):
    _inherit = 'product.template'
    
    def unlink(self):
        for rec in self:
            for product in rec.product_variant_ids:
                product.rp_check_pos_loyalty()
        return super().unlink()


class InheritProduct(models.Model):
    _inherit = 'product.product'
    
    def rp_check_pos_loyalty(self):
        for loyalty in self.env['loyalty.program'].sudo().search([]):
            rules_product_ids = loyalty.mapped('rule_ids').mapped('product_ids').filtered(lambda x:x.id==self.id)
            if len(rules_product_ids)>0:
                raise UserError('该产品在折扣&会员的方案[%s]的条件规则中被使用，不能删除。' % loyalty.name)
            reward_product_ids = loyalty.mapped('reward_ids').mapped('reward_product_id').filtered(lambda x:x.id==self.id)
            if len(reward_product_ids)>0:
                raise UserError('该产品在折扣&会员的方案[%s]的奖励规则中被使用，不能删除。' % loyalty.name)
            trigger_product_ids = loyalty.mapped('trigger_product_ids').filtered(lambda x:x.id==self.id)
            if len(trigger_product_ids)>0:
                raise UserError('该产品在礼品卡和电子钱包的方案[%s]中被使用，不能删除。' % loyalty.name)

    def unlink(self):
        for rec in self:
            rec.rp_check_pos_loyalty()
        return super().unlink()
